#include "Thread.h"
#include "Logger.h"
#include "CurrentThread.h"
#include <semaphore.h>
namespace mymuduo {

std::atomic_int Thread::numCreated_ {0};

Thread::Thread(ThreadFunc func, const std::string &name) 
    : started_(false)
    , joined_(false)
    , tid_(0)
    , func_(std::move(func))
    , name_(name) {

    setDefaultName();

}

Thread::~Thread() {
    if(started_ && !joined_) {
        thread_->detach(); // thread 类提供了分离线程的方法
    }
}

// 一个 thread 对象记录的就是一个新线程的详细信息
void Thread::start() { 
    if(!started_) {
        started_ = true;
        sem_t sem;
        sem_init(&sem, false, 0);
        // 开启线程
        thread_ = std::shared_ptr<std::thread>(new std::thread([&](){
            tid_ = currentthread::tid(); // 获取线程 tid
            sem_post(&sem);
            func_(); // 开启一个新线程，执行该线程函数
        }));

        // 这里必须等待获取上面新创建的线程的 tid 值
        sem_wait(&sem);
    } else {
        LOG_FATAL("%s start twice\n", name_.c_str());
    }
}

void Thread::join() {
    joined_ = true;
    thread_->join();
}

void Thread::setDefaultName() {
    int num = ++numCreated_;
    if(name_.empty()) {
        char buf[32];
        snprintf(buf, sizeof(buf), "Thread%d", num);
        name_ = std::string(buf);
    }
}

}